package com.javalearn.demo.controller;

import com.javalearn.demo.pojo.Result;
import com.javalearn.demo.pojo.User;
import com.javalearn.demo.service.UserService;
import com.javalearn.demo.utils.JwtUtil;
import com.javalearn.demo.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    // 注册功能
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {

            // 查询用户
            User u = userService.findByUserName(username);
            if (u == null) {
                // 没有占用
                // 注册
                userService.register(username, password);
                return Result.success();
            } else {
                return Result.error("用户名已占用");
            }
    }

    // 登录功能
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
        // 根据用户名查询用户
            User loginUser = userService.findByUserName(username);
        // 判断用户是否存在
            if (loginUser == null) {
                return Result.error("用户名错误");
            }

        // 判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            // 登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token) {
        // 根据用户名查询用户
        Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String)map.get("username");

        User user = userService.findByUserName(username);
        return Result.success(user);
    }

}

